const fileRouter = require('koa-router')()
const fs = require('fs')
const fse = require('fs-extra')
const path = require('path')
const gltfPipeline = require("gltf-pipeline")
const processGltf = gltfPipeline.processGltf

// 文件上传
fileRouter.post('/file/upload', (ctx: any) => {
  const file = ctx.request.files.file; // 获取上传文件

  // 创建可读流
  const reader = fs.createReadStream(file.filepath);
  const filePath = path.join(__dirname, '../upload/') + `${file.originalFilename}`

  // 创建可写流
  const upStream = fs.createWriteStream(filePath)
  // 可读流通过管道写入可写流
  reader.pipe(upStream);

  // 压缩 gltf 文件
  const gltf = fse.readJsonSync(filePath);
  const options = {
    dracoOptions: {
      compressionLevel: 10
    }
  }
  processGltf(gltf, options).then(function (results: any) {
    fse.writeJsonSync(path.join(__dirname, '../../public/resource/model/') + `scene.gltf`, results.gltf)
  })

  ctx.body = {
    code: 200,
    message: '上传成功',
    data: {}
  }
})

// 大文件上传
const UPLOAD_DIR = path.resolve(__dirname, '../upload')
fileRouter.post('/file/upload2', async (ctx: any) => {
  const file = ctx.request.files.file

  const fileNameArr = file.originalFilename.split('.')
  // 存放切片的目录
  const chunkDir = `${UPLOAD_DIR}/${fileNameArr[0]}`

  // 没有目录就创建目录
  if (!fse.existsSync(chunkDir)) {
    await fse.mkdir(chunkDir)
  }
  // 原文件名.index - 每个分片的具体地址和名字
  const dPath = path.join(chunkDir, fileNameArr[1])
  // 将分片文件移动到本次上传大文件的临时目录
  await fse.move(file.filepath, dPath, { overwrite: true })


  ctx.body = {
    code: 200,
    message: '上传成功',
    data: {}
  }
})

// 合并文件
fileRouter.post('/file/merge', async (ctx: any) => {
  const file = ctx.request.files.file
  const filename = file.originalFilename
  const fname = filename.split('.')[0]
  const chunkDir = `${UPLOAD_DIR}/${fname}`
  const chunks = await fse.readdir(chunkDir)
  chunks.sort((a: string, b: string) => Number(a) - Number(b))


  chunks.forEach((chunk: any) => {
    fse.appendFileSync(
      path.join(UPLOAD_DIR, filename),
      fse.readFileSync(`${chunkDir}/${chunk}`)
    )
  })

  fse.removeSync(chunkDir)

  ctx.body = {
    code: 200,
    message: '合并成功',
    data: {}
  }
})

module.exports = fileRouter
